require"mqtt"
require"protoair"
require"linkout"
require"linkin"
module(...,package.seeall)

local ready = false

function isReady() return ready end

local function enPwd(s)
	local tmp,ret,i = 0,""
	for i=1,string.len(s) do
		tmp = bit.bxor(tmp,string.byte(s,i))
		if i % 3 == 0 then
			ret = ret..string.char(tmp)
			tmp = 0
		end
	end
	return string.tohex(ret)
end

local co_monitor = sys.taskInit(function()
	sys.waitUntil('IMSI_READY')
	if sim.getstatus() then
		while true do
			if sys.wait(1800000) == nil then
				sys.restart('monitor timeout')
			end
		end
	end
end)

sys.taskInit(
	function()
		while true do
			while not socket.isReady() do sys.waitUntil('IP_READY_IND') end
			local imei = misc.getimei()
			local mqttc = mqtt.client(imei,600,imei,enPwd(imei))
			--阻塞执行MQTT CONNECT动作，直至成功
			while not mqttc:connect(nvm.get("addr"),nvm.get("port"),nvm.get("prot")) do
				sys.wait(2000)
			end
			ready = true
			--订阅主题
			if mqttc:subscribe(
				{
					[linkout.enTopic("devparareq/+")]=1,
					[linkout.enTopic("deveventreq/+")]=1,
					[linkout.enTopic("set")]=1,
					[linkout.enTopic("updpbreq/+")]=1,
					[linkout.enTopic2("+",misc.getimei(),"single/stod/+")]=1,
					[linkout.enTopic2("+",misc.getimei(),"group/+/stod/+")]=1
				}
			) then
				linkout.init()
				while true do
					if not linkin.procMsg(mqttc) then log.error("linkin.procMsg error") break end
					if not linkout.procMsg(mqttc) then log.error("linkout.procMsg error") break end
					coroutine.resume(co_monitor, 'feed monitor')
				end
				linkout.unInit()
			end
			ready = false
			--断开MQTT连接
			mqttc:disconnect()
		end
	end
)
